---
sidebar_position: 4
description: Learn about TTL indexes in FerretDB.
---

# Time-To-Live (TTL) indexes

import CodeBlock from '@theme/CodeBlock'
import CreateTTLIndexRequest from '!!raw-loader!./ttl-indexes/1-create-ttl-index.request.js'
import InsertTTLDataRequest from '!!raw-loader!./ttl-indexes/2-insert-ttl-data.request.js'

TTL (Time-To-Live) indexes are useful when you need documents to be deleted automatically after a certain time.
It's ideal for temporary records, logs, or session data that you don't want to keep indefinitely.
Unlike most indexes that focus on query performance, TTL indexes serve a different purpose by ensuring outdated data is deleted periodically and efficiently.

They are single-field indexes and not allowed as multi-field/compound indexes.

:::note

- Documents inserted before the index was created may not be affected until an insert or update operation occurs.
  It is recommended to create the TTL index before inserting documents.
- The cleanup of expired documents is a background operation that runs every 60 seconds, so deletion may not be immediate.

:::

## Creating a TTL index

A TTL index is created using the `createIndex` command with the field you want to index and the `expireAfterSeconds` option set to the number of seconds before a document expires.
The field must have a `Date` type.

For example, let's create a TTL index for the `reservation.date` field in a `books` collection.

<CodeBlock language="js">{CreateTTLIndexRequest}</CodeBlock>

Let's insert a document into the `books` collection:

<CodeBlock language="js">{InsertTTLDataRequest}</CodeBlock>

After 60 seconds, the document will be deleted in the next cleanup operation.
